/**
 * axios配置
 */
import Vue from 'vue'
import axios from 'axios'
import store from '../store'
import setting from './setting'
import VueAxios from 'vue-axios'
import { Message, MessageBox } from 'element-ui'
import { envDistinguishDomain } from '@/utils/common'

Vue.use(VueAxios, axios)

// 设置统一的url
axios.defaults.baseURL = envDistinguishDomain()

/* 请求拦截器 */
axios.interceptors.request.use((config) => {
  // 添加token到header
  const token = setting.takeToken()
  if (token) {
    config.headers[setting.tokenHeaderName] = token
  }
  config.headers['X-Requested-With'] = 'XMLHttpRequest';
  return config
}, (error) => {
  return Promise.reject(error)
})

/* 响应拦截器 */
axios.interceptors.response.use((res) => {
  let headerContent = res.headers['download-info'] ?? false
  if (headerContent) {
    return res
  }
  let code = res?.data?.code || null
  if (code === null) {
    let msg = res.headers?.err ? JSON.parse(res.headers.err) : { msg: '接口请求异常' }
    Message({ message: msg.msg || '接口请求异常', type: 'error' })
  } else if (code !== 200) {
    Message({
      message: res?.data?.msg || '接口请求失败',
      type: 'error'
    })
    if ([107000, 107005, 107006].includes(code)) {  // 登录状态异常，退出登录
      goLogin(res.data.msg || '登录状态异常，请重新登录')
    }
  }

  if (res.data?.token) {
    store.dispatch('user/setToken', {
      token: res.data?.token,
      remember: true
    }).then(() => {
    })
    delete res.data.token
  }
  return res
}, (error) => {
  Message({
    message: '接口请求失败!!',
    type: 'error'
  })
  return Promise.reject(error)
})

/**
 * 跳转到登录页面
 */
function goLogin (msg) {
  MessageBox.alert(msg, '系统提示', {
    confirmButtonText: '重新登录',
    callback: () => {
      store.dispatch('user/removeToken').then(() => {
        location.replace('/login')  // 这样跳转避免再次登录重复注册动态路由
      })
    }
  })

}

export default axios
